package com.atguigu.cloud.mygateway;

import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;

import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

/**
 * 情景分析，本网站有三级会员，限制只有三级会员才能访问，一级、二级不能访问。
 */
@Component
public class MyRoutePredicatedFactory extends AbstractRoutePredicateFactory<MyRoutePredicatedFactory.Config>
{

    public MyRoutePredicatedFactory() {
        super(MyRoutePredicatedFactory.Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                String usertype = serverWebExchange.getRequest().getQueryParams().getFirst("userType");
                if (usertype==null)
                    return false;
                if (usertype.equals("3"))
                    return true;
                return false;
            }
        };
    }

    @Validated
    public static class Config {
        @Getter@Setter@NotEmpty
        private String usertype;
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList("userType");
    }

}
